<?php
/**
 * 静态 function
 */
class framework_static_function {
    private static $numLength = 14;
    /**
     * 远程获取文件
     */
    public static function curl_file_get_contents($durl) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($durl));
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        // curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
        curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        // print_r(curl_getinfo($ch));exit;
        // var_dump(curl_error($ch));
        curl_close($ch);
        // var_dump($data);
        // exit;
        return $data;
    }

    /**
     * @param $url
     * @param $para
     * @param string $method
     * @return mixed
     */
    public static function http_curl($url, $para, $method = "POST") {
        $data_string = http_build_query($para);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        } else {
            //get
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if($result == false || empty($result)) {
            $info = curl_getinfo($ch);
            framework_static_function::write_log($url."\t".json_encode($para)."\t".json_encode($info), 'curl_error_logs');
        }
        curl_close($ch);
        return $result;
    }

    public static function https_curl($url, $para, $cert = null) {
        if (strpos($url, 'PATr0003') === false) {
            static_function::write_log($url . "\t" . $para, 'rlms_interface');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);

        //测试数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($cert == null) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); ;
            curl_setopt($ch, CURLOPT_CAINFO, $cert);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type:application/json',
            'Content-Length: ' . strlen($para)
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        if (!empty($result)) {
            return json_decode($result, true);
        } else {
            return false;
        }
    }

    /**
     * 获取page URL
     */
    public static function curPageURL() {
        if (SERVER_GET_IP)
            $_SERVER["SERVER_NAME"] = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : $_SERVER["SERVER_NAME"];
        $pageURL = 'http';

        if (isset($_SERVER["HTTPS"])) {
            if ($_SERVER["HTTPS"] == "on")
                $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    /**
     * 获取 URL
     */
    public static function curURL() {
        $pageURLArr = explode("/", self::curPageURL());
        unset($pageURLArr[count($pageURLArr) - 1]);
        return implode("/", $pageURLArr) . "/";
    }

    public static function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }

    /**
     * 检查文件夹
     */
    public static function mkdirs($path, $mode = 0777) {
        $dirs = explode('/', $path);
        $pos = strrpos($path, ".");
        if ($pos === false) {
            // note: three equal signs
            // not found, means path ends in a dir not file
            $subamount = 0;
        } else {
            $subamount = 1;
        }

        for ($c = 0; $c < count($dirs) - $subamount; $c++) {
            $thispath = "";
            for ($cc = 0; $cc <= $c; $cc++) {
                $thispath .= $dirs[$cc] . '/';
            }
            // echo $thispath . "<br />";
            if (!file_exists($thispath)) {
                //print "$thispath<br>";
                mkdir($thispath, $mode);
            }
        }
    }

    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准json
     *
     * @access	public
     *
     * @author	jonah.fu
     * @date	2012-04-19
     *
     * @return   string
     *
     */
    public static function output_json($array, $num = true, $jsonHeader = true) {
        header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
        $jsonHeader && header('Content-type: application/json;charset=utf-8');
        header("Pramga: no-cache");
        header("Cache-Control: no-cache");
        if ($num) {
            exit(json_encode((array)($array), JSON_NUMERIC_CHECK));
        } else {
            exit(json_encode((array)($array)));
        }
    }
	/**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准jsonp
     *
     * @access  public
     *
     * @author  jonah.fu
     * @date    2012-04-19
     *
     * @return   string
     *
     */
    public static function output_jsonp($array,$callback='callback',$num = true, $jsonHeader = true) {
    	header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
    	$jsonHeader && header('Content-type: application/json;charset=utf-8');
    	header("Pramga: no-cache");
    	header("Cache-Control: no-cache");
    	if ($num) {
    		exit($callback.'('.json_encode((array)($array), JSON_NUMERIC_CHECK).');');
    	} else {
    		exit($callback.'('.json_encode((array)($array)).');');
    	}
    }

    /**
     * 魔术引号
     */
    public static function strip_array($var) {
        return is_array($var) ? array_map("self::strip_array", $var) : addslashes(htmlspecialchars($var));
    }

    /**
     * 圆周计算
     *
     */
    public static function rad($d) {
        return bcmul($d, (bcdiv('3.1415926535898', '180', self::$numLength)), self::$numLength);
    }

    /**
     * 经纬度之间获取距离
     */
    public static function GetDistance($lat1, $lng1, $lat2, $lng2) {
        $EARTH_RADIUS = 6378.137;
        $radLat1 = self::rad($lat1);
        //echo $radLat1;
        $radLat2 = self::rad($lat2);
        $a = bcsub($radLat1, $radLat2, self::$numLength);
        $b = bcsub(self::rad($lng1), self::rad($lng2), self::$numLength);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = bcmul($s, $EARTH_RADIUS, self::$numLength);
        $s = round($s * 10000) / 10000;
        return $s;
    }

    public static function debug($var) {
        if ($_COOKIE['debug'] == 'jkdc') {
            print_r('<pre style="text-align: left">');
            print_r((array)$var);
            print_r('</pre>');
        }
    }

    public static function write_log($logs, $file_name = '') {
        $logs = date('Y-m-d H:i:s') . "\t" . $logs . "\r\n";
        if (empty($file_name)) {
            $file = APP_PATH . '/../logs/' . date("Y/m/d") . '/sites.txt';
        } else {
            $file = APP_PATH . '/../logs/' . date("Y/m/d") . '/' . $file_name . '.txt';
        }

        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        error_log($logs, 3, $file);
    }

    public static function history_back($msg = '') {
        if ($msg) {
            $msg = "alert('" . $msg . "');";
        }
        echo "<script>" . $msg . "history.go(-1);</script>";
        die ;
    }

    public static function rand_money() {
        return mt_rand(1, 9) / 100;
    }

    //封装rlms请求数据成json格式
    public static function rlms_json($para) {
        $data_string = "{";
        foreach ($para as $key => $val) {
            $data_string .= $key . ":'" . $val . "',";
        }
        $data_string = substr($data_string, 0, -1);
        $data_string .= "}";
        return $data_string;
    }

    //短信通知开发
    public static function notice_developer($msg, $mobile = '') {
        $mobile = $mobile ? $mobile : DEVELOPER_MOBILE;
        static_message::send($mobile, $msg);
    }

    /**
     *
     */
    public static function set_cookie($key, $value, $time = '24*60*60') {
        setCookie($key, $value, $time, '/');
    }

	/**
	 * 将ip转为整数
	 */
	public static function ipton($ip){
		$ip_arr=explode('.',$ip);//分隔ip段
		foreach ($ip_arr as $value){
			$iphex=dechex($value);//将每段ip转换成16进制
			if(strlen($iphex)<2){//255的16进制表示是ff，所以每段ip的16进制长度不会超过2
				$iphex='0'.$iphex;//如果转换后的16进制数长度小于2，在其前面加一个0
			//没有长度为2，且第一位是0的16进制表示，这是为了在将数字转换成ip时，好处理
			}
			$ipstr.=$iphex;//将四段IP的16进制数连接起来，得到一个16进制字符串，长度为8
		}
		return hexdec($ipstr);//将16进制字符串转换成10进制，得到ip的数字表示
	}

	/**
	 * 将整数转为ip
	 */
	public static function ntoip($n){
		$iphex=dechex($n);//将10进制数字转换成16进制
		$len=strlen($iphex);//得到16进制字符串的长度
		if(strlen($iphex)<8){
			$iphex='0'.$iphex;//如果长度小于8，在最前面加0
			$len=strlen($iphex); //重新得到16进制字符串的长度

			for($i=0,$j=0;$j<$len;$i=$i+1,$j=$j+2){//循环截取16进制字符串，每次截取2个长度
				$ippart=substr($iphex,$j,2);//得到每段IP所对应的16进制数
				$fipart=substr($ippart,0,1);//截取16进制数的第一位
				if($fipart=='0'){//如果第一位为0，说明原数只有1位
					$ippart=substr($ippart,1,1);//将0截取掉
				}
				$ip[]=hexdec($ippart);//将每段16进制数转换成对应的10进制数，即IP各段的值
			}
			return implode('.', $ip);//连接各段，返回原IP值
		}
	}
	
	public static function outputXmlJson($contents) {
		$dom = new DOMDocument;
		$response = $contents;
		$response = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/s", "$1", $response);
		@$dom->loadXML($response);
		if (!$dom->documentElement) {
		    exit('{"error":"error"}');
		}
		$xml = new SimpleXMLElement($response);
		return json_encode($xml);
	}
	
	/**
	 * 将1000转换成1,000这种格式
	 * @param string $str
	 */
	
	
	public static function moneyToString($str){
		if($str == 0){
			return 0;
		}
		$strlen = strlen($str);
		$num_3 = floor($strlen/3);
		$remainder = $strlen%3;
		$newstring = '';
		$start = 0;
		for($i = 0; $i <= $num_3; $i++){
			if($i == 0 && $remainder != 0 && $strlen > 3){
				$newstring .= substr($str,0,$remainder) . ',';
				$start += $remainder;
				continue;
			}
			if(($start+3) < $strlen){
				$newstring .= substr($str,$start,3) . ',';
			} else {
				$newstring .= substr($str,$start,3);
			}
			$start +=  3;
		}
		return $newstring;
	}
	
	/*
	 * 从文件/数组中导入定义常量
	 * @source 数组文件路径 或 数组
	 * @type 定义常量的来源格示 file 文件 / array 数组
	 */
	public static function export_define($source = null , $type = 'file') {
		switch ($type) {
			case 'file':
				if(empty($source) || !is_string($source)) {
					return FALSE;
				}
				$source = include($source);
				break;
			case 'array':
				if(empty($source) || !is_array($source)) {
					return FALSE;
				}
				break;
			default :
				if(empty($source) || !is_string($source)) {
					return FALSE;
				}
				$source = include($source);
				break;
		}
		if(!is_array($source) || empty($source)) {
			return FALSE;
		}
		foreach($source as $key => $value){
			if(is_string($value) || is_numeric($value) || is_bool($value) || is_null($value)) {
				if(!defined($value)){
					define(strtoupper($key),$value);
				}
			}
		}
		return $source;
	}

    /*
     * @desc 判断ios还是android
     * @author wangshui
     * */
    public static function getos(){
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $rs = "undefined";
        if(preg_match('/android/i', $agent) && $_GET["from"] == "app"){
            $rs = "android";
        }else if(preg_match('/(iphone|ios)/i', $agent) && $_GET["from"] == "app"){
            $rs = "ios";
        }
        return $rs;
    }
}
?>
